//
// Created by Administrator on 2021/10/20.
//
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <climits>

using namespace std;

class Solution {
public:
    string truncateSentence(string s, int k) {
        // 找到第k个空格 返回这个空格之前的字符串
        string ans;
        int spaceNum = 0;
        for (int i = 0; i < s.size() and spaceNum < k; ++i) {
            if (s[i] == ' ')
                ++spaceNum;
            ans.push_back(s[i]);
        }
        if (*(ans.end() - 1) == ' ')
            ans.pop_back();
        return ans;
    }

    string truncateSentence2(string s, int k) {
        string ans;
        s += ' ';
        unsigned int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (s[i] == ' ') --k;
            if (k == 0) {
                ans = s.substr(0, i);
                break;
            }
        }
        return ans;
    }

};

int main() {
    Solution solution;
    cout << solution.truncateSentence2("Hello how are you Contestant", 4) << endl;
    return 0;
}
